//
//  AppDelegate.m
//  RSW.IOS
//
//  Created by zhaiqiuqiu on 16/10/25.
//  Copyright © 2016年 com.xtion.crm. All rights reserved.
//

#import "AppDelegate.h"

#import <WeexSDK/WXSDKEngine.h>
#import <WeexSDK/WXDebugTool.h>
#import <WeexSDK/WXLog.h>
#import <WeexSDK/WXAppConfiguration.h>

#import "LoginViewController.h"
#import "IntroductionViewController.h"
#import "SimpleLoginViewController.h"
#import "AddSimpleViewController.h"

#import "AppDelegate+InitTransformURLBlock.h"
#import "AppDelegate+ObserverNetWorkChange.h"
#import "AppDelegate+ApplicationWillEnterForeground.h"
#import "AppDelegate+CheckVersionFromAppStore.h"
#import "AppDelegate+Private.h"
#import "AppDelegate+EntityRegister.h"
#import "MineViewController.h"

// 引 JPush功能所需头 件
#import "JPUSHService.h"
// iOS10注册APNs所需头 件
#ifdef NSFoundationVersionNumber_iOS_9_x_Max 
#import <UserNotifications/UserNotifications.h> 
#endif
// 如果需要使 idfa功能所需要引 的头 件(可选)
#import <AdSupport/AdSupport.h>

@interface AppDelegate ()<JPUSHRegisterDelegate>

@end

@implementation AppDelegate


- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    // Override point for customization after application launch.
    self.window = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
    self.window.backgroundColor    = [UIColor whiteColor];
    [self.window makeKeyAndVisible];
    
    [self appConfig];
    [self initRootViewController];
    [self initFieldRelation];
    [self initCustomerFieldRelation];
    [self initWeex];
    //[self initSP];
    
    [self initJPush:launchOptions];
    
    //延长启动图时间
    [NSThread sleepForTimeInterval:2.0];
    
    return YES;
}

- (void)initRootViewController
{
    Class viewControllerCls = NULL;
    if([[XLGContext getDocumentSysCfgDictionary][XLGContentIsFirstRun] boolValue] == YES)
    {
        viewControllerCls = [LoginViewController class]; 
    }
    else
    {
        viewControllerCls = [LoginViewController class];
    }
    
    XUINavigationController *nav = [[XUINavigationController alloc]initWithRootViewControllerClass:viewControllerCls];
    for(UIView *view in [nav.navigationBar subviews])
    {
        if([view isMemberOfClass:NSClassFromString([NSString stringWithFormat:@"_%@%@%@",@"UINavigation",@"Bar",@"Background"])])
        {
            for(UIView *v in view.subviews)
            {
                if([v isMemberOfClass:[UIImageView class]])
                {
                    v.hidden = YES;
                }
                break;
            }
            break;
        }
    }
    
    self.window.rootViewController = nav;
}

- (void)initSP
{
    self.window.rootViewController.view.alpha = 0;
    UIImageView *splashImageView = [[UIImageView alloc]initWithImage:[UIImage imageNamed:@"img_splash"]];
    [self.window addSubview:splashImageView];
    [UIView animateWithDuration:0.7 animations:^{
        self.window.rootViewController.view.alpha = 1.0;
    } completion:^(BOOL finished) {
        [self.window addSubview:splashImageView];
        [splashImageView removeFromSuperview];
    }];
}
- (void)appConfig
{
    [XMSFileHelper initPath];
    
    NSString *path = [[XMSFileHelper documentPath] stringByAppendingPathComponent:SYSCFGFE];
    
    if (YES != [XMSFileHelper isFileDirExist:path])
        [XMSFileHelper copySource:[[NSBundle mainBundle] pathForResource:SYSCFGF ofType:@"plist"] toTarget:path];
    
    [self simpleDownloadManagerTransferURLBlock];
    
    [self httpChannelTransferURLBlock];

    [self downloadManagerTransferURLBlock];

    [self addObserverNetWorkChange];
    
    [XMSNetWorkReachability initReachability:^XMSNetWorkReachability *
     {
         return [XMSNetWorkReachability reachabilityForInternetConnection];
     }];
    
    [CProtocolTransformType setHTTPSRESTUserNumber:^NSString *
     {
         return [NSString stringValue:[XLGContext context].m_szUsernumber];
     }];
    
    [CRequestChannelPoolShell initRequestChannelPool];
    
    [self initUIStyle];
    
    [self initVersion];
    
    _bgtask = UIBackgroundTaskInvalid;
}

- (void)initJPush:(NSDictionary *)launchOptions
{
    NSString *advertisingId = [[[ASIdentifierManager sharedManager] advertisingIdentifier] UUIDString];
    // Required
    // notice: 3.0.0及以后版本注册可以这样写,也可以继续 旧的注册 式
    JPUSHRegisterEntity * entity = [[JPUSHRegisterEntity alloc] init];
    entity.types = JPAuthorizationOptionAlert|JPAuthorizationOptionBadge|JPAuthorizationOptionSound;
    if ([[UIDevice currentDevice].systemVersion floatValue] >= 8.0) {
        // 可以添加 定义categories
        // NSSet<UNNotificationCategory *> *categories for iOS10 or later
        // NSSet<UIUserNotificationCategory *> *categories for iOS8 and iOS9
    }
    [JPUSHService registerForRemoteNotificationConfig:entity delegate:self];
    
    // Required
    // init Push
    // notice: 2.1.5版本的SDK新增的注册 法,改成可上报IDFA,如果没有使 IDFA直接传nil
    // 如需继续使 pushConfig.plist 件声明appKey等配置内容,请依旧使 [JPUSHService setupWithOption:launchOptions] 式初始化。
    [JPUSHService setupWithOption:launchOptions
                           appKey:appKey
                          channel:channel
                 apsForProduction:isProduction
            advertisingIdentifier:advertisingId];
}

- (void)initVersion
{
    //版本配置文件处理
    [XLGContext updateSyscfgplistCompletion:^(NSInteger nOldbuildno,NSInteger nNewbuildno)
     {
         if (nNewbuildno > nOldbuildno)
         {
             NSArray *arPath = nil;
             [XMSFileHelper isDirEmpty:[XMSFileHelper documentPath] containFiles:&arPath];
             for (NSString *s in arPath)
             {
                 NSString *szPath = [[XMSFileHelper documentPath] stringByAppendingPathComponent:s];
                 NSString *szFiletype = [[XMSFileHelper getFileAttributes:szPath] fileType];
                 if ([szFiletype isEqualToString:NSFileTypeDirectory])
                 {
                     [XMSFileHelper deleteFileDir:szPath];
                 }
             }
         }
     }];
}

- (void)initUIStyle
{
    [[UINavigationBar appearance] setBarTintColor:[UIColor colorWithHex:mcrmSAASUIShinColorTextStyle2196F3Color]];
    [[UINavigationBar appearance] setTintColor:[UIColor whiteColor]];
    [[UINavigationBar appearance] setTitleTextAttributes:@{NSForegroundColorAttributeName:[UIColor whiteColor]}];
    [[UINavigationBar appearance] setBackgroundColor:[UIColor colorWithHex:mcrmSAASUISkinColorTextStyle0x25b6edColor]];
    
    [[UITableView appearance] setBackgroundColor:[UIColor colorWithHex:mcrmSAASUISkinColorTextStylef1f4f7Color]];
    [[UITableView appearance] setSeparatorColor:[UIColor colorWithHex:0xdedfe0]];
    
    [CUIStyleSkinManager initUIStyleSkin:EUIStyleSkinTypeCustomSearchBar complete:^(CUIStyleSkin *uiss)
     {
         XUISearchBarStyleSkin *ss = (XUISearchBarStyleSkin *) uiss;
         ss.searchFieldReturnKeyType = UIReturnKeyDone;
         ss.searchFieldBorderStyle = UITextBorderStyleRoundedRect;
     }];
    [CUIStyleSkinManager initUIStyleSkin:EUIStyleSkinTypeRefreshHeaderView complete:^(CUIStyleSkin *uiss)
     {
         CRefreshHeaderViewStyleSkin *ss = (CRefreshHeaderViewStyleSkin *) uiss;
         ss.stateTextAlignment = NSTextAlignmentCenter;
         ss.presentType = XUIRefreshHeaderViewPresentTypeDefault;
         ss.refreshIndicatorAnimatedType = XUIRefreshIndicatorAnimatedTypeDefault;
         ss.refreshingAnimatedType = XUIRefreshingAnimatedTypeImagePlayCycle;
         ss.titleTextColor = [UIColor colorWithR:17 G:130 B:255 A:1];
         ss.arRefreshingImage = [NSArray arrayWithObjects:[NSNumber numberWithFloat:1],[NSValue valueWithCGSize:CGSizeMake(24, 15)], [UIImage imageNamed:@"refresh_indicator_1.png"],[UIImage imageNamed:@"refresh_indicator_2.png"],[UIImage imageNamed:@"refresh_indicator_3.png"],[UIImage imageNamed:@"refresh_indicator_4.png"],[UIImage imageNamed:@"refresh_indicator_5.png"],nil];
     }];
    [CUIStyleSkinManager initUIStyleSkin:XUIStyleSkinTypeGroupTableView complete:^(CUIStyleSkin *uiss)
     {
         XUIGroupTableViewStyleSkin *ss = (XUIGroupTableViewStyleSkin *)uiss;
         ss.separatorColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStyleLineColor];
         ss.backgroundColor = [UIColor colorWithHex:mcrmSAASUISkinColorTextStyleTableViewBackgroundColor];
     }];
    
    [UIApplication sharedApplication].statusBarStyle = UIStatusBarStyleLightContent;
}

- (void) checkVersion
{
    [NSNotificationCenter addObserver:self dictionarySelector:@{XLGCheckNewVersionXLGCheckNewVersionResultNotification:@"observerXLGCheckNewVersionXLGCheckNewVersionResultNotification:"}];
    
    if([XLGContext context].hadNewVsersion == YES && [XLGContext context].forceUpdate == YES)
        [NSNotificationCenter postNotification:XLGCheckNewVersionXLGCheckNewVersionResultNotification userInfo:@{XLGCheckNewVersionXLGCheckNewVersionResultNewKey:@(YES)}];
}

- (void)initWeex
{
    //业务配置，非必需
    [WXAppConfiguration setAppGroup:@"AliApp"];
    [WXAppConfiguration setAppName:@"WeexDemo"];
    [WXAppConfiguration setAppVersion:@"1.0.0"];
    
    //初始化SDK环境
    [WXSDKEngine initSDKEnviroment];
    
    //设置Log输出等级：调试环境默认为Debug，正式发布会自动关闭。
    [WXLog setLogLevel:WXLogLevelDebug];
}

+ (AppDelegate *)App
{
    return (AppDelegate *) [[UIApplication sharedApplication] delegate];
}

+ (void)stopNetWorkChangeCheckTimer
{
    [[AppDelegate App] invalidateObserverNetWorkChangeCheckTimer];
    
    [[AppDelegate App] invalidateEnterForegroundCheckTimer];
    
    [[AppDelegate App]->_reachability stopNotifier];
}

- (void)dissmissPresentViewController:(BOOL)animated
{
    if(_window.subviews.count > 0)
    {
        for(UIView *view in _window.subviews)
        {
            if(view.nextResponder != nil && [view.nextResponder isKindOfClass:[UIViewController class]])
            {
                if([view.nextResponder isKindOfClass:[DoImagePickerController class]])
                {
                    [((DoImagePickerController*)view.nextResponder) dismissViewControllerAnimated:animated completion:NULL];
                }
                else if([view.nextResponder isKindOfClass:[UIImagePickerController class]])
                {
                    [((UIImagePickerController*)view.nextResponder) dismissViewControllerAnimated:animated completion:NULL];
                }
                else if([view.nextResponder isKindOfClass:[MFMessageComposeViewController class]])
                {
                    [((MFMessageComposeViewController*)view.nextResponder) dismissViewControllerAnimated:animated completion:NULL];
                }
                else if([view.nextResponder isKindOfClass:[XUIPreviewImageViewController class]])
                {
                    [((XUIPreviewImageViewController*)view.nextResponder) dismissPreviewImageViewController:animated];
                }
            }
        }
    }
}

#pragma --
#pragma -- UIApplicationDelegate
- (void)applicationWillResignActive:(UIApplication *)application {
    // Sent when the application is about to move from active to inactive state. This can occur for certain types of temporary interruptions (such as an incoming phone call or SMS message) or when the user quits the application and it begins the transition to the background state.
    // Use this method to pause ongoing tasks, disable timers, and invalidate graphics rendering callbacks. Games should use this method to pause the game.
}


//- (void)applicationDidEnterBackground:(UIApplication *)application {
//    // Use this method to release shared resources, save user data, invalidate timers, and store enough application state information to restore your application to its current state in case it is terminated later.
//    // If your application supports background execution, this method is called instead of applicationWillTerminate: when the user quits.
//}


- (void)applicationWillEnterForeground:(UIApplication *)application {
    // Called as part of the transition from the background to the active state; here you can undo many of the changes made on entering the background.
}


- (void)applicationDidBecomeActive:(UIApplication *)application {
    // Restart any tasks that were paused (or not yet started) while the application was inactive. If the application was previously in the background, optionally refresh the user interface.
    
    //检查AppStore版本
    [[RSWMessageOperation new] requestAsyncBlock:^
     {
         [self chectVersionFromAppStore];
     }];
}


- (void)applicationWillTerminate:(UIApplication *)application {
    // Called when the application is about to terminate. Save data if appropriate. See also applicationDidEnterBackground:.
}

- (void)applicationDidEnterBackground:(UIApplication *)application
{
    [self dissmissPresentViewController:NO];
    
    void (^suspendFun)()=^
    {
        [RSWMessageOperation suspendOperatePushNotification];
        
        [[XMSNetWorkReachability reachability] stopNotifier];
        
        [XLGUpdateSession suspendUpdateSessionTimer];
        
        [XLGSendQueueManager suspendSendQueueManager];
        
        [XLGDownloadManager suspendDownloadManager];
        
        [XLGServiceTime endService];
        
        [CRequestChannelPoolShell stopRequestRunLoop];
    };
    
    void(^singleFun)() = ^
    {
        if([XLGContext context].m_bIsoffline == NO && [XMSBackgroundMaintain isNeedMaintain]==YES)
        {
            DispatchMainThreadAsync(^
                                    {
                                        ReleaseObj(_timer);
                                        [[UIApplication sharedApplication] endBackgroundTask:_bgtask];
                                        _bgtask = UIBackgroundTaskInvalid;
                                        [[UIApplication sharedApplication] clearKeepAliveTimeout];
                                        [XMSBackgroundMaintain startMaintainWithSuspendBlock:^
                                         {
                                             [XMSSingleQueue runAsyncBlock:^
                                              {
                                                  suspendFun();
                                              }];
                                         }];
                                    });
        }
        else
            suspendFun();
    };
    
    void(^backgroundFun)()=^
    {
        _bgtask = [[UIApplication sharedApplication] beginBackgroundTaskWithExpirationHandler:^
                   {
                   }];
        
        _timer = [[XMSTimerBlock alloc] initTimerWithTimeInterval:0 repeats:NO block:^(XMSTimerBlock *timer)
                  {
                      _timer = nil;
                      
                      [[UIApplication sharedApplication] endBackgroundTask:_bgtask];
                      _bgtask = UIBackgroundTaskInvalid;
                  }];
        [_timer setFireDateFromNowToTimeInterval:5];
        
        [_reachability stopNotifier];
        
        [self invalidateEnterForegroundCheckTimer];
        
        [self invalidateObserverNetWorkChangeCheckTimer];
    };
    
    [XMSSingleQueue runAsyncBlock:^
     {
         singleFun();
     }];
    backgroundFun();
}

/*
#ifdef __IPHONE_8_0
- (void)application:(UIApplication *)application didRegisterUserNotificationSettings:(UIUserNotificationSettings *)notificationSettings
{
    [application registerForRemoteNotifications];
}
#endif

- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
{
    NSString *s =[NSString stringWithFormat:@"%@",deviceToken];
    s = [s substringFromIndex:1];
    s = [s substringToIndex:s.length - 1];
    [RSWMessageOperation setTokenID:s];
    
    [RSWMessageOperation bindPushAsyncCompletion:^(NSInteger nResult, BOOL bResult, NSError *error)
     {
         [RSWMessageOperation getChatOfflineMessage:YES complete:^(NSInteger nResult){}];
     }];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error
{
    [RSWMessageOperation bindPushAsyncCompletion:^(NSInteger nResult, BOOL bResult, NSError *error)
     {
         [RSWMessageOperation getChatOfflineMessage:YES complete:^(NSInteger nResult){}];
     }];
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
#ifdef DEBUG
    NSLog(@"Receive Notify: %@", userInfo);
#endif
    
    [RSWMessageOperation savePushNotification:userInfo];
}
*/

#pragma --
#pragma JPush
- (void)application:(UIApplication *)application
didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {
    /// Required - 注册 DeviceToken
    [JPUSHService registerDeviceToken:deviceToken];
    
    NSString *s =[NSString stringWithFormat:@"%@",deviceToken];
    s = [s substringFromIndex:1];
    s = [s substringToIndex:s.length - 1];
    [RSWMessageOperation setTokenID:s];
}

- (void)application:(UIApplication *)application didFailToRegisterForRemoteNotificationsWithError:(NSError *)error {
    //Optional
    NSLog(@"did Fail To Register For Remote Notifications With Error: %@", error);
}

#pragma --
#pragma JPUSHRegisterDelegate
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center willPresentNotification:(UNNotification *)notification withCompletionHandler:(void (^)(NSInteger))completionHandler {
    // Required
    NSDictionary * userInfo = notification.request.content.userInfo;
    if([notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]
        ]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(UNNotificationPresentationOptionAlert);
    // 需要执 这个 法,选择 是否提醒 户,有Badge、Sound、Alert三种类型可以选择设置
}
// iOS 10 Support
- (void)jpushNotificationCenter:(UNUserNotificationCenter *)center didReceiveNotificationResponse:(UNNotificationResponse *)response withCompletionHandler:(void (^)())completionHandler {
    // Required
    NSDictionary * userInfo = response.notification.request.content.userInfo;
    if([response.notification.request.trigger isKindOfClass:[UNPushNotificationTrigger class]]) {
        [JPUSHService handleRemoteNotification:userInfo];
    }
    completionHandler(); // 系统要求执 这个 法
}
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo fetchCompletionHandler:(void (^)(UIBackgroundFetchResult))completionHandler {
    // Required, iOS 7 Support
    [JPUSHService handleRemoteNotification:userInfo];
    completionHandler(UIBackgroundFetchResultNewData);
}

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo {
    // Required,For systems with less than or equal to iOS6
    [JPUSHService handleRemoteNotification:userInfo];
}
    
#pragma --
#pragma observer
-(void)observerXLGCheckNewVersionXLGCheckNewVersionResultNotification:(NSNotification*)noti
{
    BOOL newVersion = [noti.userInfo[XLGCheckNewVersionXLGCheckNewVersionResultNewKey] boolValue];
    if(newVersion == YES)
    {
        BOOL forceUpdate = [XLGContext context].forceUpdate;
        
        NSDictionary *dic = [XLGContext getDocumentSysCfgDictionary];
        
        BOOL remind = [dic[XLGContextUpdateInfo][XLGContextUpdateInfoRemind] boolValue];
        
        if(forceUpdate == NO && remind == NO)
            return;
        
        NSString *newVersionName = dic[XLGContextUpdateInfo][XLGContextUpdateInfoNewVersionName];
        
        NSString *tips = [NSString megerStringWithTag:dic[XLGContextUpdateInfo][XLGContextUpdateInfoTip] tag:@"\r\n"];
        
        [XUIAlertView alertViewWithTitle:[NSString stringWithFormat:@"发现%@版本",newVersionName] message:tips cancelButtonTitle:@"立即更新" otherButtonTitles:forceUpdate == YES ? nil : @[@"以后再说"] clickBlock:^(NSInteger nClickindex)
         {
             if(nClickindex == 1)
             {
                 [XLGContext remindNewVersion:NO];
             }
             else
             {
                 [XLGUserConfig writeCurrentUserConfigWithDictionary:@{XLGUserConfigDefaultKeyAutoLogin:@(0)}];
                 
                 [[UIApplication sharedApplication] openURL:[NSURL URLWithString:dic[XLGContextUpdateInfo][XLGContextUpdateInfoNewVersionHttp]]];
                 
                 exit(0);
             }
         }];
    }
}

@end
